package com.info33.platform.business.utils;

import com.info33.platform.common.util.ApplicationContextUtil;
import com.info33.platform.doc.entity.DocFileDetail;
import com.info33.platform.doc.service.DocFileDetailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class FileUtil {
    private static final DocFileDetailService docFileDetailService = ApplicationContextUtil.getBean(DocFileDetailService.class);

    public static <T> List<T> convertVOByFile(List<? super T> doList, Class<T> voClass, Map<String, String> map) {
        List<T> voList = new ArrayList<>();
        try {
            T vo;
            for (Object entity : doList) {
                vo = voClass.newInstance();
                BeanUtils.copyProperties(entity, vo);
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    Field resource = entity.getClass().getDeclaredField(entry.getKey());
                    Field target = voClass.getDeclaredField(entry.getValue());

                    if (ObjectUtils.isEmpty(resource) && ObjectUtils.isEmpty(target)) {
                        System.out.println("没有此属性");
//                        voList.add(vo);
                        break;
                    }
                    resource.setAccessible(true);
                    Type type = resource.getAnnotatedType().getType();
                    String[] split = type.getTypeName().split("\\.");
                    DocFileDetail detail;
                    if (split[split.length - 1].equals("Long")) {
                        Long resourceValue = (Long) resource.get(vo);
                        detail = docFileDetailService.getById(resourceValue);
                        target.setAccessible(true);
                        target.set(vo, detail);
                    }

                    if (split[split.length - 1].equals("String")) {
                        String resourceValue = (String) resource.get(vo);

                        if (StringUtils.isNotBlank(resourceValue)) {
                            List<String> strings = Arrays.asList(resourceValue.split(","));
                            List<DocFileDetail> docFileDetails = docFileDetailService.listByIds(strings);
                            target.setAccessible(true);
                            target.set(vo, docFileDetails);
                        }

                        List list = new ArrayList();
                        list.stream().mapToLong(null);
                    }
                }
                voList.add(vo);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return voList;
    }

}
